package com.gjy.spring.boot3;

import org.springframework.boot.DefaultBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.EventPublishingRunListener;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.EnvironmentPostProcessorApplicationListener;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.core.io.support.SpringFactoriesLoader;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-12-18 11:33:26
 */
public class Boot4App {

    public static void main(String[] args) throws Exception {
        StandardEnvironment env = new StandardEnvironment(); // 系统变量，properties，yaml
        // 添加额外的配置文件 【第五步的时候被添加】
        env.getPropertySources().addLast(new ResourcePropertySource(new ClassPathResource("application.yml")));
        // 第三步
        env.getPropertySources().addFirst(new SimpleCommandLinePropertySource(args));
        // 第四步
        ConfigurationPropertySources.attach(env); // 把名字不一致的统一，统一用-获取

        for (PropertySource<?> source : env.getPropertySources()) {
            System.out.println(source);
        }

        // 第五步,配置后处理器, ApplicationListener 监听器读取配置做增强
        SpringApplication app = new SpringApplication();
        app.addListeners(new EnvironmentPostProcessorApplicationListener()); // 添加环境变量监听器
        EventPublishingRunListener publisher = new EventPublishingRunListener(app, args);

        System.out.println(">>> 增强前");
        for (PropertySource<?> p1 : env.getPropertySources()) {
            System.out.println("p1 = " + p1);
        }
        /*ConfigDataEnvironmentPostProcessor processor1 = new ConfigDataEnvironmentPostProcessor(new DeferredLogs(), new DefaultBootstrapContext());
        processor1.postProcessEnvironment(env, app);*/
        // 通过事件发送机制
        publisher.environmentPrepared(new DefaultBootstrapContext(), env);

        System.out.println(">>> 增强后");
        for (PropertySource<?> p2 : env.getPropertySources()) {
            System.out.println("p2 = " + p2);
        }
        // 优先使用systemProperties(-DJAVA_HOME=aaa),找不到再使用systemEnvironment
        System.out.println("env.getProperty(\"JAVA_HOME\") = " + env.getProperty("JAVA-HOME"));

        for (String name : SpringFactoriesLoader.loadFactoryNames(EnvironmentPostProcessor.class, app.getClassLoader())) {
            System.out.println("name = " + name);
        }

    }
}
